package com.activity.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import event.MessageEvent;

import com.activity.App;
import com.activity.OpusDetailActivity;
import com.activity.PersonActivity;
import com.activity.adapter.Person1Adapter;
import com.activity.adapter.PersonAdapter;
import com.activity.bean.OpusBean;
import com.api.param.AddWorkParam;
import com.api.param.CommentParam;
import com.api.param.PageParam;
import com.api.viewModel.LoginVM;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.donkingliang.groupedadapter.layoutmanger.GroupedGridLayoutManager;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.activity.widget.PictureEditView;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;

import static androidx.recyclerview.widget.StaggeredGridLayoutManager.GAP_HANDLING_NONE;

public class HomeNewFragment extends BaseListViewFragment <LoginVM>{

    private Person1Adapter personalAdapter;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private int selectIndex;

    @Override
    public void createView() {
        super.createView();

        personalAdapter = new Person1Adapter(mContext);

//       recycleView.setPadding(ScreenUtil.dp2px(this,0),ScreenUtil.dp2px(this,10),ScreenUtil.dp2px(this,0),0);

        recycleView.setAdapter(personalAdapter);

        viewModel.praisePosition.observe(this,res->{
            MessageEvent messageEvent=  new MessageEvent(MessageEvent.MESSAGE_EVENT_WORK_PRAISE);
            messageEvent.worksId = personalAdapter.data.get(res).getWorksid();
            messageEvent.praiseNum = viewModel.praise.getValue();
            EventBus.getDefault().post(messageEvent);

        });

        personalAdapter.personListener = new PersonAdapter.personListener() {
            @Override
            public void praiseClick(int childPosition) {

                selectIndex =childPosition;
                CommentParam param1 = new CommentParam();
                param1.worksid = personalAdapter.data.get(childPosition).getWorksid();
                addSubscription(viewModel.addworkspraise(param1,selectIndex));
            }
        };

        recycleView.addItemDecoration(new PictureEditView.SquareLayoutItemDecoration(ScreenUtil.dp2px(mContext,0),ScreenUtil.dp2px(mContext,0),2));

        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        staggeredGridLayoutManager.setGapStrategy(GAP_HANDLING_NONE);

        recycleView.setItemAnimator(null);

        GroupedGridLayoutManager gridLayoutManager =  new GroupedGridLayoutManager(mContext, 2, personalAdapter);
        recycleView.setLayoutManager(staggeredGridLayoutManager);
        viewModel.workError.observe(this,error->{
            if(error){
                headerFreshEnd();
            }else {
                pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)-1)+"";
                footerFreshEnd();
            }
        });


        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                staggeredGridLayoutManager.invalidateSpanAssignments();
//                int[] first = new int[2];
//                staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(first);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
//                    staggeredGridLayoutManager.invalidateSpanAssignments();
//                }

            }


            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);



            }
        });

        viewModel.work.observe(this,data->{

            if(data.isHeader){

                personalAdapter.data.clear();
                personalAdapter.data.addAll(data.getResult());

                headerFreshEnd();
            }else
            {
                personalAdapter.data.addAll(data.getResult());
                if(data.getResult().size()>0){
                    footerFreshEnd();
                }else
                {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }


            showEmpty(personalAdapter.data.size()==0);


//            if(personalAdapter.data.size()>0){
//                GroupedGridLayoutManager gridLayoutManager = new GroupedGridLayoutManager(this, 2, personalAdapter);
//                recycleView.setLayoutManager(gridLayoutManager);
//            }else {
//                recycleView.setLayoutManager(new LinearLayoutManager(this));
//            }



            personalAdapter.notifyDataChanged();



        });
        headerFreshing();
        personalAdapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {

                if(personalAdapter.data.size()>0) {
                    Bundle param  = new Bundle();
                    Gson gson =new Gson();
                    param.putString("param", gson.toJson(personalAdapter.data.get(childPosition)));

                    ActivityUtil.startActivity(mContext,OpusDetailActivity.class,param);
                }

            }
        });


    }

    protected void headerFreshing() {
        pageParam.pagenum ="1";
        refreshLayout.resetNoMoreData();
        addSubscription(viewModel.getWorkHome(pageParam,true));
    }

    PageParam pageParam = new PageParam();
    protected void footerFreshing() {
        pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)+1)+"";

        addSubscription(viewModel.getWorkHome(pageParam,false));
    }

    @Override
    public void initStatusBar() {
        ImmersionBar.with(this)
                .titleBar(rootView.findViewById(R.id.nav_bar))
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.black)
                .init();
    }

    @Override
    public void onMessageEventBus(MessageEvent event) {
        super.onMessageEventBus(event);
         if(event.getMessage()==MessageEvent.MESSAGE_EVENT_WORK_PRAISE){
            boolean flag =false;
            int index=0;


            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksid().equals(event.worksId)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
                OpusBean data=   personalAdapter.data.get(index);

                data.setWorkifpraise(event.praiseNum);
                if(event.praiseNum.equals("1")){
                    data.setWorkspraisenum((Integer.valueOf(data.getWorkspraisenum())+1)+"" );
                }else {
                    data.setWorkspraisenum((Integer.valueOf(data.getWorkspraisenum())-1)+"" );
                }




                personalAdapter.notifyChildChanged(0,index);


            }
        }

        if(event.getMessage() == MessageEvent.MESSAGE_EVENT_UPDATE_USER){

            personalAdapter.notifyDataChanged();



            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksuserid().equals(App.getInstance().getAccount().getUserid())){
                    personalAdapter.data.get(i).setUsernickname(App.getInstance().getAccount().getUsernickname());
                }
            }


        }
        if(event.getMessage() == MessageEvent.MESSAGE_EVENT_DELETE_WORKS){


            boolean flag =false;
            int index=0;
            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksid().equals(event.worksId)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
                personalAdapter.data.remove(index);
                personalAdapter.notifyDataChanged();
            }


        }if(event.getMessage()==MessageEvent.MESSAGE_EVENT_UPDATE_WORKS){
            boolean flag =false;
            int index=0;

            Gson gson  = new Gson();
            AddWorkParam addWorkParam = gson.fromJson(event.addwork, AddWorkParam.class);
            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksid().equals(addWorkParam.worksid)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
                OpusBean data=   personalAdapter.data.get(index);
                data.setWorkstitle(addWorkParam.title);
                data.setWorkscontent(addWorkParam.content);
                data.setWorkstags(addWorkParam.tags);
                data.setWorkspics(addWorkParam.pics);
                data.setWorkssizes(addWorkParam.sizes);




                personalAdapter.notifyDataChanged();


            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden == false) {

            headerFreshing();
        }
    }
    @Override
    public void onResume() {
        super.onResume();

        if (isHidden()) {

        } else {
            headerFreshing();
        }


    }
}
